import { createRouter, createWebHistory } from 'vue-router'
import Blog from '../views/Blog.vue'
import Role from '../views/Role.vue'
import Child from '../views/Child.vue'
import ReactApp from '../views/ReactApp.vue'
import microApp from '@micro-zoe/micro-app'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/blog'
    },
    {
      path: '/blog',
      name: 'blog',
      component: Blog
    },
    {
      path: '/role',
      name: 'role',
      component: Role
    },
    {
      path: '/child',
      name: 'child',
      component: Child
    },
    {
      path: '/react-app',
      name: 'react-app',
      component: ReactApp,
      meta: { microApp: true }
    }
  ]
})

// 用于跟踪路由切换状态
let isNavigating = false

// 路由切换前清理子应用
router.beforeEach((to, from, next) => {
  // 避免重复处理
  if (isNavigating) {
    next()
    return
  }

  // 如果从微前端应用离开
  if (from.meta.microApp) {
    isNavigating = true
    const apps = microApp.getActiveApps()
    if (apps.length > 0) {
      console.log('清理活跃的子应用:', apps.map(app => app.name))
      microApp.unmountAllApps()
    }
    // 重置状态
    setTimeout(() => {
      isNavigating = false
    }, 0)
  }
  next()
})

export default router